<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Node extends Base
{

    protected $name = 'user_node';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id,team_id,my_boxes,team_boxes,small_boxes,big_boxes');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,level_id,team_id,my_boxes,team_boxes,small_boxes,big_boxes');
    }


    /**
     * 原点 2020年8月22日16:25:27 记录节点关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_id -- 推荐人的ID
     * @return array
     */
    public function record($uid, $code, $node_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($node_id) {
                $p_id = $node_id;
                $insert = [];
                while ($node = User::where('id', $p_id)->field('id,code,node_id')->find()) {
                    if ($node) {
                        $data['uid'] = $node->id;
                        $data['code'] = $node->code;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_id = $node->node_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队盒数
     * 原点 2021年12月28日11:50:17 更新团队盒数
     */
    public static function renewTeamBoxes($amount, $uid, $key = 'team_boxes')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }



    //大小区盒数
    public static function small_boxes($u_id): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $u_id)->field('id,uid,algebra')->order('algebra', 'asc')->select();//团队列表
            foreach ($list as $r=>$item) {
                    $zt_user = User::where(['node_id'=>$item->uid,'is_active'=>2])->field('id,my_boxes,team_boxes,my_boxes+team_boxes as boxes')->order('boxes','desc')->find();//直推人员最大的
                    if($zt_user)
                    {
                        $small = $item->user->team_boxes-$zt_user->boxes;//小区
                        User::update(['small_boxes'=>$small,'big_boxes'=>$zt_user->boxes], ['id' => $item->uid]);//修改小区业绩
                    }

            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }



    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $level = TeamLevel::where('id', '>', $item->user->team_id)
                    ->where('small_boxes', '<=', $item->user->small_boxes)
                    ->where('big_boxes', '<=', $item->user->big_boxes)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['team_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //贡献奖
    public static function contribute($uid)
    {
        try {
            $contribute = Cache::get('system')['contribute'];
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $level = Level::find($item->user->level_id);
                $user_node = parent::where('new_uid', $uid)->where('uid', $item->uid)->find();
//                dump($user_node->algebra);dump($level->layers);
                if($user_node->algebra<=$level->layers)
                {
                    Relation::awardPrizes($item->user->id, $contribute, '贡献奖', '+', $uid, 1);
                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function sale_reward($uid,$boxes_num): array
    {
        try {

            $list = parent::with('user')->where(['new_uid'=>$uid])
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            $sale_total = 0;
            $team_id = 0;
            $flat_id = 0;
            $user_id = 0;
            foreach ($list as $item) {
                $level = TeamLevel::find($item->user->team_id);
                if($team_id<$item->user->team_id)
                {
                    $amounts = $level->sale*$boxes_num;
                    $amount = $amounts - $sale_total;
                    Relation::awardPrizes($item->user->id,$amount,'销售奖', '+',$uid, 2);
                    Relation::coaching_award($item->user->id,$amount); //辅导奖
                    $team_id = $item->user->team_id;
                    $sale_total = $amounts;
                    $user_id = $item->user->id;

                }elseif($team_id==$item->user->team_id&&$flat_id!=$team_id)
                {
                    $all_id = parent::where('new_uid', $uid)->column('uid');
                    if (!empty($all_id)) {
                        $users = User::whereIn('id', $all_id)->where('team_id',$item->user->team_id)->column('id');
                        $key = array_search($user_id,$users);
                        if($key!=false)
                        {
                            unset($users[$key]);
                        }
                        $num = count($users);
//                        $flat_amount = bcdiv($level->flat_tp, (string)$num,2);
                        $flat_amount = round($level->flat_tp*$boxes_num/$num, 2);
                        foreach ($users as $k=>$v)
                        {
                            Relation::awardPrizes($v,$flat_amount,'平级奖', '+',$uid, 3);
                        }
                    }
                    $flat_id = $item->user->team_id;
                }


            }

            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
